#!/usr/bin/paython
#coding=utf-8

starts = dict()
ends = dict()
sources = []


for line in open(r'/Users/lczgywzyy/.csmetrics/Aliases.txt'):
    line = line.strip().split(' ')
    startpoint = line[0]
    endpoint = line[1]
    if startpoint == endpoint:
        continue
    else:
        if startpoint in starts:
            starts[startpoint].append(endpoint)
        else:
            starts[startpoint] = [endpoint]

        if endpoint in ends:
            ends[endpoint].append(startpoint)
        else:
            ends[endpoint] = [startpoint]

s = starts.keys()
e = ends.keys()
for source in s:
    if source not in e:
        sources.append(source)

def process(path,v):
    # print 'now process:',path,v
    if v in path:
        # 每条路径的起点不可能在环上，因此index不为0
        # print path,v
        next = []
        for index, val in enumerate(path):
            if val == v:
                next.append(path[index+1])
        loop = 1
    else:
        loop = 0
    if v in starts:
        for e in starts[v]:
            if loop and e in next:
                if len(starts[v]) == 1:
                    f.write(' '.join(path) + ' -1 \n')
                else:
                    continue
            else:
                path.append(v)
                process(path, e)
                path.pop()
    else:   # 如果v是路径末端
        path.append(v)
        f.write(' '.join(path)+' -1 \n')
        path.pop()

f = open('/Users/lczgywzyy/.csmetrics/termid_list.txt', 'w')
for s in sources:
    for e in starts[s]:
        process([s],e)
f.close()
print 'over'
